package com.mfangsoft.zhuangjialong.app.weixin.util;

import java.io.IOException;
import java.net.URI;
import java.security.InvalidAlgorithmParameterException;
import java.util.HashMap;
import java.util.Map;


import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mfangsoft.zhuangjialong.app.weixin.model.WeiXinPhone;
import com.mfangsoft.zhuangjialong.app.weixin.model.WeixinReturnValue;
import com.mfangsoft.zhuangjialong.common.utils.AESUtil;
import com.mfangsoft.zhuangjialong.common.utils.Base64;
import com.mfangsoft.zhuangjialong.common.utils.CacheUtil;
import com.mfangsoft.zhuangjialong.common.utils.HttpClientUtil;
import com.mfangsoft.zhuangjialong.common.utils.HttpRequest;
import com.mfangsoft.zhuangjialong.common.utils.RedisUtils;
import com.mfangsoft.zhuangjialong.common.utils.StreamUtils;
import com.mfangsoft.zhuangjialong.common.utils.SysConstant;


/**
* @description：
* @author：Jianghua.Tang 
* @date：2017年2月28日
* 
*/

public class WeiXinUtil {
    
	/************************ 登陆后换取session****************/
	public static WeixinReturnValue getSessionKey(String appID,String appSecret,String js_code){
		String responseContent = HttpRequest.sendGet("https://api.weixin.qq.com/sns/jscode2session",
				"appid="+appID+"&secret="+appSecret+"&js_code="+js_code+"&grant_type=authorization_code");
		ObjectMapper objectMapper = new ObjectMapper();
			try {
				System.out.println(objectMapper.writeValueAsString(responseContent));
				return objectMapper.readValue(responseContent, WeixinReturnValue.class);
			} catch (IOException e) {
				e.printStackTrace();
			}
		return null;
	}
	 
	/************************ 通过encryptedData获取用户信息 ****************/
	public static WeixinReturnValue decodeUserInfo(String encryptedData, String iv, String session_key) {
		try {
			byte[] resultByte = AESUtil.INSTANCE.decrypt(Base64.decode(encryptedData), Base64.decode(session_key),
					Base64.decode(iv));
			if (null != resultByte && resultByte.length > 0) {
				String userInfo = new String(resultByte, "UTF-8");
				System.out.println(userInfo);
				ObjectMapper objectMapper = new ObjectMapper();
				objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
				return objectMapper.readValue(userInfo, WeixinReturnValue.class);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvalidAlgorithmParameterException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	/************************ 通过encryptedData获取用户绑定手机号 ****************/
	public static WeiXinPhone decodeUserPhone(String encryptedData, String iv, String session_key) {
		try {
			byte[] resultByte = AESUtil.INSTANCE.decrypt(Base64.decode(encryptedData), Base64.decode(session_key),
					Base64.decode(iv));
			if (null != resultByte && resultByte.length > 0) {
				String userInfo = new String(resultByte, "UTF-8");
				System.out.println(userInfo);
				ObjectMapper objectMapper = new ObjectMapper();
				objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
				return objectMapper.readValue(userInfo, WeiXinPhone.class);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvalidAlgorithmParameterException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	
	/*
	 * 获取accesstoken
	 */
	public static String getAccessToken(String APPID,String APPSECRET) throws Exception {
			String responseContent = HttpRequest.sendGet("https://api.weixin.qq.com/cgi-bin/token",
					"grant_type=client_credential&appid="+APPID+"&secret="+APPSECRET);
			ObjectMapper objectMapper = new ObjectMapper();
			WeixinReturnValue json = objectMapper.readValue(responseContent, WeixinReturnValue.class);
			String accessToken = "";
			if (json != null) {
				if (json.getAccess_token() != null) {
					accessToken = json.getAccess_token();
					Long expiresIn = json.getExpires_in();
					RedisUtils.setWithTimeLimit(SysConstant.WEIXINSHAREACCESSTOKEN, accessToken, expiresIn-200);
//					CacheUtil.Cache.put(SysConstant.WEIXINSHAREACCESSTOKEN, accessToken);
				}
			}
			return accessToken;
		}
	 
	/**
	 * 获取ticket
	 * @return
	 * @throws Exception
	 */
	public static String getTicket(String access_token) throws Exception {
		/*String responseContent = HttpRequest.sendGet("https://api.weixin.qq.com/cgi-bin/ticket/getticket",
				"access_token=" + access_token + "&type=jsapi");*/
		String responseContent = HttpRequest.sendGet("https://api.weixin.qq.com/cgi-bin/ticket/getticket",
				"access_token=" + access_token + "&type=jsapi");
		ObjectMapper objectMapper = new ObjectMapper();
		WeixinReturnValue json = objectMapper.readValue(responseContent, WeixinReturnValue.class);
		String ticket = "";
		if (json != null) { 
			if (json.getErrcode() == 0) {
				ticket = json.getTicket();
				Long expiresIn = json.getExpires_in();
				RedisUtils.setWithTimeLimit(SysConstant.WEIXINSHARETICKET, ticket, expiresIn-200);
			}
		}
		return ticket;
	}
	
	/**
	 * 生成小程序二维码
	 * @param args
	 * @throws Exception 
	 */
	public static String makeQRCode(String fileName,String logoUrl,String scene,Long user_id,String APPID,String APPSECRET,boolean ishyaline) throws Exception{
		Map<String , Object> line_color = new HashMap<>();
		line_color.put("r", "0");
		line_color.put("g", "0");
		line_color.put("b", "0");
		Map<String , Object> param = new HashMap<>();
		param.put("scene", scene);
		param.put("width", 430);
		param.put("auto_color", false);
		param.put("line_color", line_color);
		ObjectMapper om = new ObjectMapper();
		String paramStr = om.writeValueAsString(param);
		String access_token = RedisUtils.getValue(SysConstant.WEIXINSHAREACCESSTOKEN);
		System.out.println(access_token);
		if(access_token == null || !SysConstant.WEIXINSHAREACCESSTOKEN.equals(access_token)){
			access_token=getAccessToken(APPID, APPSECRET);
		}
		URI uri =new URI("http://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+access_token);
		return StreamUtils.saveToImgByInputStream(fileName,HttpClientUtil.sendPostForJsonRetrurnContent(uri, paramStr),logoUrl,ishyaline);
	}
	/**
	 * 创建卡券
	 * @param 
	 * @throws Exception 
	 */
	/*public static String coupon(String access_token)throws Exception{
		String buffer = null;
		File file = new File("");
		BufferedInputStream in = new BufferedInputStream(new FileInputStream("C://Users//Administrator//Pictures//123.jpg"));
		String r1 = HttpRequest.sendPost("https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token="+access_token+"&buffer="+in,"");
		System.out.println(r1);
		String responseContent = HttpRequest.sendPost("https://api.weixin.qq.com/card/create", access_token);
		System.out.println(responseContent);
		return "123";
		 	String result = null;  
	        File file = new File("C://Users//Administrator//Desktop//123.jpg");  
	        String s =  file.getName();
	        System.out.println("Mime Type of " + file.getName() + " is " +  
                    new MimetypesFileTypeMap().getContentType(file));  
	        if (!file.exists() || !file.isFile()) {  
	            throw new IOException("文件不存在");  
	        }  
	        *//** 
	        * 第一部分 图片上传部分
	        *//*  
	        URL urlObj = new URL("http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token="+ access_token);  
	       // URL urlObj = new URL("http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token="+ access_token + "&type=image");  
	        HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();  
	        con.setRequestMethod("POST"); // 以Post方式提交表单，默认get方式  
	        con.setDoInput(true);  
	        con.setDoOutput(true);  
	        con.setUseCaches(false); // post方式不能使用缓存  
	        con.setRequestProperty("Connection", "Keep-Alive");// 设置请求头信息  
	        con.setRequestProperty("Charset", "UTF-8");  
	        String BOUNDARY = "----------" + System.currentTimeMillis();   // 设置边界  
	        con.setRequestProperty("Content-Type", "multipart/form-data; boundary="+ BOUNDARY);  
	        // 请求正文信息  
	        // 第一部分：  
	        StringBuilder sb = new StringBuilder();  
	        sb.append("--"); // 必须多两道线  
	        sb.append(BOUNDARY);  
	        sb.append("\r\n");  
	        sb.append("Content-Disposition: form-data;name=\"file\";filename=\""+ file.getName() + "\"\r\n");  
	        sb.append("Content-Type:application/octet-stream\r\n\r\n");  
	        byte[] head = sb.toString().getBytes("utf-8");  
	        // 获得输出流  
	        OutputStream out = new DataOutputStream(con.getOutputStream());  
	        // 输出表头  
	        out.write(head);  
	        // 文件正文部分  
	        // 把文件已流文件的方式 推入到url中  
	        DataInputStream in = new DataInputStream(new FileInputStream(file));  
	        int bytes = 0;  
	        byte[] bufferOut = new byte[1024];  
	        while ((bytes = in.read(bufferOut)) != -1) {  
	        out.write(bufferOut, 0, bytes);  
	        }  
	        in.close();  
	        // 结尾部分  
	        byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线  
	        out.write(foot);  
	        out.flush();  
	        out.close();  
	        StringBuffer buffer = new StringBuffer();  
	        BufferedReader reader = null;  
	        try {  
	        // 定义BufferedReader输入流来读取URL的响应  
	        reader = new BufferedReader(new InputStreamReader(con.getInputStream()));  
	        String line = null;  
	        while ((line = reader.readLine()) != null) {  
		        //System.out.println(line);  
		        buffer.append(line);  
	        }  
	        if(result==null){  
	        	result = buffer.toString();  
	        }  
	        } catch (IOException e) {  
	        	System.out.println("发送POST请求出现异常！" + e);  
	        	e.printStackTrace();  
	        throw new IOException("数据读取异常");  
	        } finally {  
	        	if(reader!=null){  
	        reader.close();  
	        }  
	        } 
	        JSONObject jsonObject1 = new JSONObject(); 
	       
	        JSONObject jsonObject2 = new JSONObject(); 
	        jsonObject2.put("logo_url","http://mmbiz.qpic.cn/mmbiz_jpg/e9HT6vdIysCWibS710O6S5waaPNGAuuKibTdhTNjic8Uy5x6hib1Qcfck8YxMvs8PqmaKKIqybG260iceNv2DEicJ41g/0");
	        jsonObject2.put("code_type","CODE_TYPE_TEXT");
	        jsonObject2.put("brand_name","测试");
	        jsonObject2.put("title","测试title");
	        jsonObject2.put("color","Color010");
	        jsonObject2.put("notice","请出示二维码");
	        jsonObject2.put("description","不可与其他优惠同享");
	        JSONObject jsonObject3 = new JSONObject(); 
	        jsonObject3.put("quantity",50000);
	        jsonObject2.put("sku",jsonObject3);
	        JSONObject jsonObject4 = new JSONObject(); 
	        jsonObject4.put("type1","DATE_TYPE_FIX_TIME_RANGE");
	        jsonObject4.put("begin_timestamp","1500366352166");
	        jsonObject4.put("end_timestamp","1500366407343");
	        jsonObject2.put("date_info",jsonObject4);
	        jsonObject1.put("base_info",jsonObject2);
	        JSONObject jsonObject7 = new JSONObject();
	        jsonObject7.put("least_cost", 50);
	        jsonObject1.put("advanced_info",new JSONObject());
	        jsonObject1.put("deal_detail","优惠券专用，填写优惠详情");
 
	        JSONObject jsonObject5 = new JSONObject(); 
	        jsonObject5.put("card_type","GROUPON");
	        jsonObject5.put("groupon",jsonObject1);
	        JSONObject jsonObject6 = new JSONObject(); 
	        jsonObject6.put("card",jsonObject5);
	        
	        
	        Gson gson = new Gson();
	        String json = gson.toJson(jsonObject6);//json转String类型
			String responseContent = HttpRequest.sendPost("https://api.weixin.qq.com/card/create?access_token="+access_token, json);
			System.out.println(responseContent);
	      
	        return ""; 
	}*/
	/**
	 * 创建会员卡
	 * @param picture 
	 * @param 
	 * @throws Exception 
	 */
	/*public static String member(String access_token, String picture)throws Exception{
		JSONObject jsonObject1 = new JSONObject();
		JSONObject card = new JSONObject();
		JSONObject member_card = new JSONObject();
		JSONObject base_info = new JSONObject();
		JSONObject advanced_info = new JSONObject();
		JSONObject abstractt = new JSONObject();
		JSONObject custom_cell1 = new JSONObject();
		JSONObject bonus_rule = new JSONObject();
		JSONObject sku = new JSONObject();
		JSONObject date_info = new JSONObject();
		date_info.put("type","DATE_TYPE_PERMANENT");
		sku.put("quantity",100);
		bonus_rule.put("cost_money_unit", 100);
		bonus_rule.put("increase_bonus", 1);
		bonus_rule.put("max_increase_bonus", 200);
		bonus_rule.put("init_increase_bonus", 10);
		bonus_rule.put("cost_bonus_unit", 5);
		bonus_rule.put("reduce_money", 100);
		bonus_rule.put("least_money_to_use_bonus", 1000);
		bonus_rule.put("max_reduce_bonus", 50);
		custom_cell1.put("name","使用入口2");
		custom_cell1.put("tips","激活后显示");
		custom_cell1.put("url","http://www.kaolaj.com/shop-web/login.html");
		abstractt.put("abstract","微信餐厅推出多种新季菜品，期待您的光临");
		base_info.put("logo_url", "http://mmbiz.qpic.cn/mmbiz_jpg/e9HT6vdIysCWibS710O6S5waaPNGAuuKibTdhTNjic8Uy5x6hib1Qcfck8YxMvs8PqmaKKIqybG260iceNv2DEicJ41g/0");
		base_info.put("code_type", "CODE_TYPE_TEXT");
		base_info.put("brand_name", "方向品牌");
		base_info.put("title", "超级巨星王者会员卡");
		base_info.put("color", "Color010");
		base_info.put("notice", "使用时向考拉家出示此券");
		base_info.put("service_phone", "020-88888888");
		base_info.put("description", "不可与优惠同享");
		base_info.put("date_info",date_info);
		base_info.put("sku",sku);
		base_info.put("auto_activate",true);
		member_card.put("base_info",base_info);
		member_card.put("supply_bonus",false);
		member_card.put("supply_balance",false);
		member_card.put("prerogative","test_prerogative");
		member_card.put("auto_activate",true);//自动激活
		member_card.put("wx_activate",true);//是否一键激活
		//member_card.put("activate_url","http://www.baidu.com");
		//member_card.put("wx_activate_after_submit",true);
		//member_card.put("wx_activate_after_submit_url","http://www.kaolaj.com/shop-web/login.html");
		
		member_card.put("custom_cell1",custom_cell1);
		member_card.put("bonus_rule",bonus_rule);
		//member_card.put("discount",10);//折扣
		
		
		card.put("card_type","MEMBER_CARD");
		card.put("member_card",member_card);
		jsonObject1.put("card", card);
		System.out.println(jsonObject1);
		
		Gson gson = new Gson();
	    String json = gson.toJson(jsonObject1);//json转String类型
		String responseContent = HttpRequest.sendPost("https://api.weixin.qq.com/card/create?access_token="+access_token, json);
		System.out.println(responseContent);
		
		 return responseContent; 
	}*/
	/**
	 * 设置开卡字段接口
	 * @param card_id 
	 * @param 
	 * @throws Exception 
	 */
	/*public static String activateuserform(String access_token, String card_id)throws Exception{
		JSONObject jsonObject1 = new JSONObject();
		JSONObject service_statement = new JSONObject();
		JSONObject required_form = new JSONObject();
		service_statement.put("name", "会员守则");
		service_statement.put("url", "http://www.kaolaj.com/shop-web/login.html");
		required_form.put("can_modify", false);
		required_form.put("common_field_id_list", "['USER_FORM_INFO_FLAG_MOBILE','USER_FORM_INFO_FLAG_SEX','USER_FORM_INFO_FLAG_NAME']");
		
		jsonObject1.put("card_id",card_id);
		jsonObject1.put("service_statement", service_statement);
		jsonObject1.put("required_form", required_form);
		
		
		Gson gson = new Gson();
	    String json = gson.toJson(jsonObject1);//json转String类型
		String responseContent = HttpRequest.sendPost("https://api.weixin.qq.com/card/membercard/activateuserform/set?access_token="+access_token, json);
		
		 return responseContent; 
	}
	*/
	/**
	 * 获取开卡插件参数
	 * @param card_id 
	 * @param 
	 * @throws Exception 
	 */
	/*public static String geturl(String access_token, String card_id)throws Exception{
		JSONObject jsonObject1 = new JSONObject();
		
		jsonObject1.put("card_id",card_id);
		jsonObject1.put("outer_str", "11");
		
		System.out.println(jsonObject1);
		
		Gson gson = new Gson();
		String json = gson.toJson(jsonObject1);//json转String类型
		String responseContent = HttpRequest.sendPost("https://api.weixin.qq.com/card/membercard/activate/geturl?access_token="+access_token, json);
		JSONObject jsonObject=JSONObject.fromObject(responseContent);
		String urlStr = URLDecoder.decode((String) jsonObject.get("url"), "UTF-8");
		System.out.println(urlStr);
		
		return urlStr; 
	}*/
	/**
	 * 上传图片
	 * @param 
	 * @throws Exception 
	 */
/*	public static String sendimg(String sendUrl, String filePath)throws Exception{
		String result = null;
		File file = new File(filePath);
		if (!file.exists() || !file.isFile()) {
			throw new IOException("文件不存在");
		}
		*//**
		* 第一部分
		*//*
		URL urlObj = new URL(sendUrl);
		// 连接
		HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
		*//**
		* 设置关键值
		*//*
		con.setRequestMethod("POST"); // 以Post方式提交表单，默认get方式
		con.setDoInput(true);
		con.setDoOutput(true);
		con.setUseCaches(false); // post方式不能使用缓存
		// 设置请求头信息
		con.setRequestProperty("Connection", "Keep-Alive");
		con.setRequestProperty("Charset", "UTF-8");
		// 设置边界
		String BOUNDARY = "----------" + System.currentTimeMillis();
		con.setRequestProperty("Content-Type", "multipart/form-data; boundary="+ BOUNDARY);
		// 请求正文信息
		// 第一部分：
		StringBuilder sb = new StringBuilder();
		sb.append("--"); // 必须多两道线
		sb.append(BOUNDARY);
		sb.append("\r\n");
		sb.append("Content-Disposition: form-data;name=\"file\";filename=\""
+ file.getName() + "\"\r\n");
		sb.append("Content-Type:application/octet-stream\r\n\r\n");
		byte[] head = sb.toString().getBytes("utf-8");
		// 获得输出流
		OutputStream out = new DataOutputStream(con.getOutputStream());
		// 输出表头
		out.write(head);
		// 文件正文部分
		// 把文件已流文件的方式 推入到url中
		DataInputStream in = new DataInputStream(new FileInputStream(file));
		int bytes = 0;
		byte[] bufferOut = new byte[1024];
		while ((bytes = in.read(bufferOut)) != -1) {
		out.write(bufferOut, 0, bytes);
		}
		in.close();
		// 结尾部分
		byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线
		out.write(foot);
		out.flush();
		out.close();
		StringBuffer buffer = new StringBuffer();
		BufferedReader reader = null;
		try {
			// 定义BufferedReader输入流来读取URL的响应
			reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
			String line = null;
			while ((line = reader.readLine()) != null) {
				//System.out.println(line);
				buffer.append(line);
			}
			if(result==null){
				result = buffer.toString();
			}
		} catch (IOException e) {
			System.out.println("发送POST请求出现异常！" + e);
		e.printStackTrace();
		throw new IOException("数据读取异常");
		} finally {
			if(reader!=null){
				reader.close();
			}
		}
	
		return result; 
	}
	*/
	public static void main(String[] args) {
		try {
			String accessToken = getAccessToken("wxf275d4551f566286", "ddb54ca8b731624e9c8a95e8c79c516c");
			//		String accessToken = "daucs9gcf-LBSZXzIq57QEB1LmpkCDINYZiFSlsZK-pgcIh1QICcESZLA4tgcJMCbxToP7UJ_yAs_Xn95Fb5D4ZDagXhgYpwpl1akYIEl_GmQehfnrPqzpGShfU-XlxhZNAjAGAUIV";
			Map<String , Object> line_color = new HashMap<>();
			line_color.put("r", "0");
			line_color.put("g", "0");
			line_color.put("b", "0");
			Map<String , Object> param = new HashMap<>();
			param.put("scene", "type=1&id=2321");
			param.put("width", 430);
			param.put("auto_color", false);
			param.put("line_color", line_color);
			ObjectMapper om = new ObjectMapper();
			String paramStr = om.writeValueAsString(param);
//			String result = HttpRequest.sendPost("https://api.weixin.qq.com/wxa/getwxacode?access_token="+accessToken, paramStr);
			URI uri =new URI("http://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+accessToken);
			String path = StreamUtils.saveToImgByInputStream(null,HttpClientUtil.sendPostForJsonRetrurnContent(uri, paramStr),null,false);
		    System.out.println(path);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}
